import services from '@/services/demo';
import {
  ActionType,
  FooterToolbar,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Divider, Input,Checkbox, message,Form,Modal,Row,Col,Table,Upload } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { FormProps, UploadFile, UploadProps } from 'antd';
import React, { useRef, useState,useEffect } from 'react';
import { history } from 'umi';

const { teacherList, teacherDelete, teacherUpdate,teacherAdd } =
  services.UserController;

const TableList: React.FC<unknown> = () => {
  const [list, setList] = useState<any[]>([]);// 列表数据
  const [pageNum, setPageNum] = useState<number>(1);// 页码
  const [actionId, setActionId] = useState<string>('');// 
  const [imageUrl, setImageUrl] = useState<string>('');
  const [readImageUrl, setReadImageUrl] = useState<string>('');
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [form] = Form.useForm();
  const actionRef = useRef<ActionType>();
  const columns: ProDescriptionsItemProps<API.UserInfo>[] = [
    {
      title: '老师姓名',
      dataIndex: 'teacherName',
      // tip: '名称是唯一的 key',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '名称为必填项', 
          },
        ],
      },
    },
    {
      title: '介绍',
      dataIndex: 'description',
      hideInSearch:true,
    },
    {
      title: '语种',
      dataIndex: 'nation',
      valueType: 'textarea',
    },
    {
      title: '照片',
      dataIndex: 'photoPath',
      hideInSearch:true,
      render: (_, record) => (
        <>
          <img style={{width:'50px'}} src={record.photoPath} alt="" />
        </>
      ),
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleRemove(record.id || '')
            }}
          >
            删除
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => add(record)}
          >
            编辑
          </a> 
        </>
      ),
    },
  ];
  // 获取列表数据
  const getList = ()=>{
    teacherList({pageNum,...searchData,pageSize:10}).then((res:any)=>{
      if(res.code=='200'){
        setList(res.data.list || [])
        setTotal(res.data.total)
        
      }else{
        message.error(res.message);
      }
    })
  }
  const [searchData, setSearchData] = useState<any>({});// 搜索参数
  useEffect(()=>{
    getList()// 获取列表数据
  },[pageNum,searchData])
  const search = async (value:any) => {
    setPageNum(1)
    setSearchData({...value})
  }
  const add = (data:any={})=>{
    form.resetFields();// 重置
    handleModalVisible(true)
    if(data.id){// 编辑  
      setActionId(data.id || '')
      form.setFieldsValue({...data})
      setImageUrl(data.photoPath)
      setReadImageUrl(data.photoPath)
    }else{// 新建
      setActionId('')
      setImageUrl('')
      setReadImageUrl('')
      form.resetFields()
    }
  }
   // 删除节点
   const handleRemove = async (id:string) => {
    Modal.confirm({
      title: '确定删除此条数据？',
      content: '',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        const hide = message.loading('正在删除');
        teacherDelete({id:id}).then((res:any)=>{
          if(res.code=='200'){
            message.success('删除成功，即将刷新');
            getList()
          }else{
            message.error(res.message);
          }
          hide()
        })
        // hide()
      },
      onCancel() {
        
      },
    });
  };
  type FieldType = {
    username1?: string;
    username2?: string;
    username3?: string;
    username4?: string;
    username5?: string;
    password?: string;
    remember?: string;
  };
  
  const onFinish: FormProps['onFinish'] = (values:any) => {
    console.log('Success:', values);
    if(actionId){
      teacherUpdate({id:actionId,...values,photoPath:imageUrl}).then((res:any)=>{
        if(res.code=='200'){
          message.success('修改成功');
          handleModalVisible(false)
          getList()
        }else{
          message.error(res.message);
        }
      })
    }else{
      teacherAdd({...values,photoPath:imageUrl}).then((res:any)=>{
        if(res.code=='200'){
          message.success('提交成功');
          handleModalVisible(false)
          getList()
        }else{
          message.error(res.message);
        }
      })
    }
  };
  
  const onFinishFailed: FormProps['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  //上传
  const [loading, setLoading] = useState(false);
  const handleUpload = (e:any) => {
    let file = e.file
    if(file.status=='done'){
      const formData = new FormData();
      formData.append('file', file.originFileObj);
      fetch('/api/sys/upload', {
        method: 'POST',
        body: formData,
      }).then((res) => {
        return res.json()
      })
      .then((res) => {
        console.log(66,res)
        if(res.code=='200'){
          message.success('上传成功');
          let data = JSON.parse(res.data)
          console.log(2,data)
          setReadImageUrl(data.fileReadPath)
          setImageUrl(data.fileUploadPath)
        }else if(res.code=='401'){
          message.error(res.message);
          history.push('/login');
        }else{
          message.error(res.message);
        }
      })
      .catch(() => {
        message.error('upload failed.');
      })
      .finally(() => {
        // setUploading(false);
      });
    }
  };
  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </button>
  );
  const [total, setTotal] = useState<number>(0);// 总数
  const pageOnChange = (page:number, pageSize:number)=>{
    setPageNum(page)
  }
  return (
    <div>
      <ProTable<API.UserInfo>
        // headerTitle="查询表格"
        actionRef={actionRef}
        onSubmit={search}
        rowKey="id"
        search={{
          defaultCollapsed:false,
          labelWidth: 120,
        }}
        pagination={{
          total,
          current:pageNum,
          pageSizeOptions:[],
          pageSize:10,
          hideOnSinglePage:true,
          onChange:pageOnChange
        }}
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => add()}
          >
            新建
          </Button>,
        ]}
        dataSource={list}
        pagination={{
          hideOnSinglePage:true,
        }}
        columns={columns}
      />
      <Modal
        destroyOnClose
        title={'详情'}
        width={700}
        open={createModalVisible}
        onCancel={() => handleModalVisible(false)}
        footer={null}
      >
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 18 }}
          style={{ maxWidth: 700 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Row>
            <Col span={24}>
              <Form.Item
                label="老师姓名"
                name="teacherName"
                rules={[{ required: true, message: '请输入老师姓名' }]}
              >
                <Input style={{width:'200px'}} />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                label="图片"
                name="photoPath"
              >
                <Upload
                  name="file"
                  listType="picture-card"
                  className="avatar-uploader"
                  showUploadList={false}
                  onChange={handleUpload}
                >
                  {readImageUrl ? <img src={readImageUrl} alt="avatar" style={{ width: '100%',height:'100%' }} /> : uploadButton}
                </Upload>
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <Form.Item
                label="语种"
                name="nation"
                rules={[{ required: true, message: '请输入语种' }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                label="详细描述"
                name="description"
                rules={[{ required: true, message: 'Please input your username!' }]}
              >
                <Input.TextArea />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item wrapperCol={{ offset: 10, span: 16 }}>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default TableList;
